﻿using System;
using System.ComponentModel.Composition;
using System.IO;
using System.Xml;
using Peter.Common;
using Peter.Common.Interfaces;
using Peter.Common.Services;

namespace Peter.Logic
{
   /// <summary>
   /// Holds the data for the peter data file.
   /// </summary>
   [Export (typeof (IPeterData))]
   [PartCreationPolicy (CreationPolicy.Shared)]
   public class PeterData : IPeterData, IPartImportsSatisfiedNotification
   {
      private XmlDocument m_Document;
      private const string DATA_FILE = "Peter.dat";

      /// <summary>
      /// Gets the message box service.
      /// </summary>
      [Import (typeof(IMessageBoxService))]
      public IMessageBoxService MessageBox { get; set; }

      /// <summary>
      /// Gets the xml data for the given item stored in the data file.
      /// </summary>
      /// <param name="name">The name of the data to retrieve.</param>
      /// <returns>A serialized xml string with data.</returns>
      public string RequestData (string name)
      {
         var xml = string.Empty;
         var nodeList = this.m_Document.GetElementsByTagName (name.Replace ('.', '_'));
         if (nodeList.Count > 0)
         {
            var tag = nodeList.Item (0);
            if (tag != null)
            {
               xml = tag.InnerXml;
            }
         }
         return xml;
      }

      /// <summary>
      /// Called when a part's imports have been satisfied and it is safe to use.
      /// </summary>
      public void OnImportsSatisfied ()
      {
         this.m_Document = new XmlDocument ();
         var file = Path.Combine (CommonUtilities.GetAssemblyDirectory (), DATA_FILE);
         if (File.Exists (file))
         {
            try { this.m_Document.Load (file); }
            catch (Exception ex)
            {
               this.MessageBox.ShowError("Unable to load the peter data file: " + ex.Message);
            }
         }
      }
   }
}
